---
title: "Reference: Workflow.if() | Conditional Branching | Kastrax Docs"
description: "Documentation for the `.if()` method in Kastrax workflows, which creates conditional branches based on specified conditions."
---

# Workflow.if()

> Experimental

The `.if()` method creates a conditional branch in the workflow, allowing steps to execute only when a specified condition is true. This enables dynamic workflow paths based on the results of previous steps.

## Usage

```typescript copy showLineNumbers
workflow
  .step(startStep)
  .if(async ({ context }) => {
    const value = context.getStepResult<{ value: number }>('start')?.value;
    return value < 10; // If true, execute the "if" branch
  })
  .then(ifBranchStep)
  .else()
  .then(elseBranchStep)
  .commit();
```

## Parameters

<PropertiesTable
  content={[
    {
      name: "condition",
      type: "Function | ReferenceCondition",
      description: "A function or reference condition that determines whether to execute the 'if' branch",
      isOptional: false
    }
  ]}
/>

## Condition Types

### Function Condition

You can use a function that returns a boolean:

```typescript
workflow
  .step(startStep)
  .if(async ({ context }) => {
    const result = context.getStepResult<{ status: string }>('start');
    return result?.status === 'success'; // Execute "if" branch when status is "success"
  })
  .then(successStep)
  .else()
  .then(failureStep);
```

### Reference Condition

You can use a reference-based condition with comparison operators:

```typescript
workflow
  .step(startStep)
  .if({
    ref: { step: startStep, path: 'value' },
    query: { $lt: 10 }, // Execute "if" branch when value is less than 10
  })
  .then(ifBranchStep)
  .else()
  .then(elseBranchStep);
```

## Returns

<PropertiesTable
  content={[
    {
      name: "workflow",
      type: "Workflow",
      description: "The workflow instance for method chaining"
    }
  ]}
/>

## Error Handling

The `if` method requires a previous step to be defined. If you try to use it without a preceding step, an error will be thrown:

```typescript
try {
  // This will throw an error
  workflow
    .if(async ({ context }) => true)
    .then(someStep)
    .commit();
} catch (error) {
  console.error(error); // "Condition requires a step to be executed after"
}
```

## Related

- [else Reference](./else.mdx)
- [then Reference](./then.mdx)
- [Control Flow Guide](../../docs/workflows/control-flow.mdx)
- [Step Condition Reference](./step-condition.mdx)
